#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cerrno>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/stat.h>
#include<fcntl.h>

const std::string pathname = "/home/user_Lian/day17/shm";
const int pro_id = 0x11223344;

const int size = 4096;
const std::string filename = "fifo";

key_t Getkey()
{
    key_t key = ftok(pathname.c_str(), pro_id);
    if (key < 0)
    {
        std::cerr << "cerr: " << errno << ",errstring :" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}
std::string ToHex(int id)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0X%x", id);
    return buffer;
}

int CreateShmgetHelp(const key_t key, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        std::cerr << "cerr: " << errno << ",errstring: " << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int Creatshmid(const key_t key)
{
    return CreateShmgetHelp(key, IPC_CREAT | IPC_EXCL | 0664); // 一定是新的
}

int Getshmid(const key_t &key)
{
    return CreateShmgetHelp(key, IPC_CREAT);
}

bool Makefifo()
{
    int n = mkfifo(filename.c_str(),0666);
    if(n<0)
    {
        std::cerr<<"errno: "<<errno<<", errrstring :"<<strerror(errno)<<std::endl;
        
        return false;
    }
    std::cout<<"mkfifo success!"<<std::endl;
    return true;
}